/**@type {HTMLCanvasElement}*/
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const CANVAS_WIDTH = canvas.width = 800;
const CANVAS_HEIGHT = canvas.height = 700;

const img1 = new Image();
img1.src = "imgs/bg/layer1.png";

const img2 = new Image();
img2.src = "imgs/bg/layer2.png";

const img3 = new Image();
img3.src = "imgs/bg/layer3.png";

const img4 = new Image();
img4.src = "imgs/bg/layer4.png";

const img5 = new Image();
img5.src = "imgs/bg/layer5.png";
let gameSpeed = 1;

/**
 *  背景图类，
 *    构造函数（图片对象，速度比）
 *          速度比使背景图的移动受到全局变量 gameSpeed影响
 *          构造函数中需要控制两个相同背景图的x和y坐标（无缝轮播）
 *    update方法：
 *          修改当前图片的横坐标
 *    draw方法：
 *          重新绘制图片
 */
class Layer{
    constructor(img,speedSeed){
        this.img = img;
        this.speedSeed = speedSeed;
        this.x = 0;
        this.y = 0;       
    }
    update(){
        this.speed = gameSpeed*this.speedSeed;
        this.x = gameFrame*this.speed % 2400;
    }
    draw(){
        ctx.drawImage(this.img,this.x,this.y);
        ctx.drawImage(this.img,this.x+2400,this.y);
    }
}
const layer1 = new Layer(img1,0.2);
const layer2 = new Layer(img2,0.4);
const layer3 = new Layer(img3,0.6);
const layer4 = new Layer(img4,0.8);
const layer5 = new Layer(img5,1);
let layers = [layer1,layer2,layer3,layer4,layer5];

let gameFrame = 0 ;
function animate(){
    ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
    layers.forEach((ele)=>{
        ele.draw();
        ele.update();
    })
    gameFrame --;
    requestAnimationFrame(animate);
}

animate();

const slider = document.getElementById("slider");
document.getElementById("speedShow").innerText = slider.value;
slider.value = gameSpeed;
slider.addEventListener("change",()=>{
    gameSpeed = slider.value;
    document.getElementById("speedShow").innerText = slider.value;
})